from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.core.paginator import Paginator

from crm import models
from django.http import Http404
from django.contrib.auth.decorators import login_required

from common_libs.permissions import permission

from .utils.filter import data_filter
from . import my_admin
from . import forms
# Create your views here.

# @login_required(login_url='/login')    # 指定登录页面路径
@login_required
def index(request):
    '''显示所有APP和其下的Model'''
    # print(my_admin.enabled_admins)
    '''{'crm': {'customer': <class 'my_admin.my_admin.CustomerAdmin'>}}'''
    
    return render(request, 'my_admin/table_index.html', {'table_list': my_admin.enabled_admins})


@login_required
@permission.check_permission
def table_detail(request, app_name, table_name):
    '''显示表详细'''
    admin_class = my_admin.enabled_admins[app_name][table_name]
    # print(admin_class.base_actions)
    if request.method == 'GET':
        obj_list, conditions, orderby_key = data_filter(request, admin_class)  # 组合搜索及排序
        paginator = Paginator(obj_list, admin_class.list_per_page)  # 分页

        page = request.GET.get('page')
        query_set = paginator.get_page(page)  # 获取单页的数据

        res_dict = {'admin_class': admin_class,
                    'query_set': query_set,
                    'conditions': conditions,
                    'orderby_key': orderby_key,
                    'privious_orderby_key': request.GET.get('o', ''),
                    'page': page,
                    'search_text': request.GET.get('_q', '')}
        return render(request, 'my_admin/table_detail.html', res_dict)

    elif request.method == 'POST':
        action = request.POST.get('action')
        ids = request.POST.get('selected_ids')
        if not action:
            raise KeyError('没有选择action')
        if not ids:
            raise KeyError('没有选择数据')
        else:
            selected_objs = admin_class.model.objects.filter(id__in=ids.split(',')).all()

        if hasattr(admin_class, action):
            action_func = getattr(admin_class, action)
            return action_func(admin_class, request, selected_objs)


@login_required
@permission.check_permission
# @permission.check_permission
def obj_change(request, app_name, table_name, nid):
    '''进入修改页'''
    admin_class = my_admin.enabled_admins[app_name][table_name]
    model_form_class = forms.create_model_form(request, admin_class)
    obj = admin_class.model.objects.get(id=nid)

    if request.method == 'POST':
        form_obj = model_form_class(request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            kwargs = {'app_name': app_name, 'table_name': table_name}
            redict_url = reverse('table_detail', kwargs=kwargs)
            return redirect(redict_url)
        # else:
        #     print(form_obj.errors)
    else:
        form_obj = model_form_class(instance=obj)
    res_dict = {'form_obj': form_obj,
                'admin_class': admin_class,
                'app_name': app_name,
                'table_name': table_name,
                }
    return render(request, 'my_admin/obj_change.html', res_dict)


@login_required
@permission.check_permission
def obj_add(request, app_name, table_name ):
    '''进入添加页'''
    admin_class = my_admin.enabled_admins[app_name][table_name]
    model_form_class = forms.create_model_form(request, admin_class, is_add_form=True)
    # 只读表不可被修改
    if admin_class.readonly_table:
        raise Http404('您所执行的添加操作不被允许')

    if request.method == 'POST':
        form_obj = model_form_class(request.POST)
        if form_obj.is_valid():
            form_obj.save()
            kwargs = {'app_name':app_name, 'table_name':table_name}
            redict_url = reverse('table_detail', kwargs=kwargs)
            return redirect(redict_url)
        else:
            print(form_obj.errors)
    else:
        form_obj = model_form_class()
    res_dict = {'form_obj': form_obj, 'admin_class': admin_class, 'is_add_form':True}
    return render(request, 'my_admin/obj_add.html', res_dict)


@login_required
@permission.check_permission
def delete_confirm(request, app_name, table_name, nid):
    '''单数据进入删除确认页'''
    admin_class = my_admin.enabled_admins[app_name][table_name]
    # 只读表不可被修改
    if admin_class.readonly_table:
        raise Http404('您所执行的添加操作不被允许')
    obj = admin_class.model.objects.get(id=nid)

    res_dict = {'objs': obj,
                'app_name': app_name,
                'table_name': table_name,
                'nid': nid}

    return render(request, 'my_admin/obj_delete.html', res_dict)


@login_required
@permission.check_permission
def do_delete(request, app_name, table_name):
    '''执行删除操作'''
    admin_class = my_admin.enabled_admins[app_name][table_name]
    if admin_class.readonly_table:
        raise Http404('您所执行的添加操作不被允许')
    ids = request.POST.get('ids').split(',')
    admin_class.model.objects.filter(id__in=ids).delete()

    kwargs = {'app_name': app_name, 'table_name': table_name}
    redict_url = reverse('table_detail', kwargs=kwargs)
    return redirect(redict_url)


@login_required
@permission.check_permission
def password_reset(request, app_name, table_name, nid):
    '''修改密码'''
    admin_class = my_admin.enabled_admins[app_name][table_name]
    obj = admin_class.model.objects.get(id=nid)
    if request.method == 'GET':
        form_obj = forms.PasswordResetForm()
    elif request.method == 'POST':
        form_obj = forms.PasswordResetForm(request.POST)

        if form_obj.is_valid():
            obj.set_password(form_obj.cleaned_data['password1'])    # 更新密码
            obj.save()
            kwargs = {'app_name': app_name, 'table_name': table_name, 'nid':nid}
            url = reverse('obj_change',kwargs=kwargs)
            return redirect(url)
    res_dict = {'form_obj': form_obj,
                'nid':nid,
                'app_name':app_name,
                'table_name': table_name}
    return render(request, 'my_admin/password_reset.html',res_dict)



def test(request):
    obj = models.Customer.objects.get(id=2)
    for related_field in obj._meta.related_objects:
        # print(related_field.get_accessor_name(), type(related_field.get_accessor_name()))
        pass
    if hasattr(obj,'enrollment_set'):
        print(1111)
    return HttpResponse('test')